# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import urllib.request


class ScrapyBzPipeline:
    def open_spider(self, spider):
        self.fp = open('picture.json', 'w', encoding='utf-8')

    # item就是yield后面的book对象
    def process_item(self, item, spider):
        self.fp.write(str(item))
        return item

    # 在爬虫文件执行之后 执行的方法
    def close_spider(self, spider):
        self.fp.close()


class scrapy_bzDownloadPipeline:
    def process_item(self, item, spider):
        url = 'https://www.toopic.cn' + item.get('src')
        # 图片都会保存在booksImage文件中 需要提前创建目录 注意这里伪节省空间就没有下载图片
        # 这里的代码实测可以运行
        filename = './picturesImage/' + item.get('name') + '.jpg'

        urllib.request.urlretrieve(url=url, filename=filename)

        return item
